import axios from "axios"
import {ElMessage} from "element-plus";
import {useUserStore} from "../store/user.ts";
import router from "../router";

const service = axios.create({
    baseURL: 'http://localhost:8888/api',
    timeout: 30000
})
// 请求拦截器
service.interceptors.request.use(
    config => {
        // 在发送请求之前做些什么
        // 比如设置token
        if (config.noAuth) return config;
        const token = localStorage.getItem('token');
        if (token) {
            config.headers['Authorization'] = `Bearer-${token}`;
        }
        return config;
    },
    error => {
        // 对请求错误做些什么
        console.error(error); // for debug
        return Promise.reject(error);
    }
);

const handleExpiredToken = (response) => {
    const token = localStorage.getItem("token");
    if (! token ) return
    localStorage.removeItem("token")
    const userStore = useUserStore()
    ElMessage({
        message: response.data.message,
        type: 'error'
    })
    router.push({name : 'Dashboard'})
    userStore.$patch({
        username: '',
        id: '',
        isLogin: false,
        modalVisible: true,
    })

}


// 响应拦截器
service.interceptors.response.use(
    response => {
        // 对响应数据做点什么
        return response.data;
    },
    error => {
        // 对响应错误做点什么
        console.error('Response error', error); // for debug
        if (error.response) {
            switch (error.response.status) {
                case 408:
                    handleExpiredToken(error.response);
                    break;
                default:
                    console.error('其他错误信息');
            }
        }
        return Promise.reject(error);
    }
);

export default service;